package com.lgx.right.controller;

import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lgx.common.entity.Dictionary;
import com.lgx.common.exception.DataException;
import com.lgx.common.tree.TreeUtils;
import com.lgx.common.web.Constants;
import com.lgx.common.web.Pagination;
import com.lgx.common.web.json.Json2Utils;
import com.lgx.common.web.util.DateUtils;
import com.lgx.common.web.util.DictUtils;
import com.lgx.common.web.util.EscapeUtils;
import com.lgx.common.web.util.ListConvertToSet;
import com.lgx.right.entity.Permission;
import com.lgx.right.entity.Resource;
import com.lgx.right.entity.Role;
import com.lgx.right.entity.User;
import com.lgx.right.service.IPermissionService;
import com.lgx.right.service.IResourceService;
import com.lgx.right.service.IRoleService;
import com.lgx.right.service.IUserService;

@Controller
@RequestMapping("/user")  
public class UserController {
	
	@Autowired
	private IUserService userService;
	
	@Autowired
	private IRoleService roleService;
	
	@Autowired
	private IResourceService resourceService;
	
	@Autowired
	private IPermissionService permissionService;

	public IPermissionService getPermissionService() {
		return permissionService;
	}

	public void setPermissionService(IPermissionService permissionService) {
		this.permissionService = permissionService;
	}

	public IResourceService getResourceService() {
		return resourceService;
	}

	public void setResourceService(IResourceService resourceService) {
		this.resourceService = resourceService;
	}

	public IUserService getUserService() {
		return userService;
	}

	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

	public IRoleService getRoleService() {
		return roleService;
	}

	public void setRoleService(IRoleService roleService) {
		this.roleService = roleService;
	}
	
	@RequestMapping("/login.do")  
	public String login(HttpServletRequest request,HttpServletResponse response)	{
		String username = request.getParameter("username");
		String password = request.getParameter("passwordMD5");
		String vaildcode = request.getParameter("vaildcode");
		
		User user = (User) request.getSession().getAttribute(Constants.LOGIN_USER);
		
		if((StringUtils.isEmpty(username) || StringUtils.isEmpty(password))&& user == null)
		{
			return "login";
		}
		
		if(user != null)
		{
			return "index";
		}
		
		/* 验证码  */
		String _code = (String) request.getSession().getAttribute(Constants.VALIDATE_CODE);
		if(!vaildcode.toLowerCase().equals(_code.toLowerCase())){
			request.setAttribute("errorMsg", "验证码为空或输入不正确！");
			return "login";
		}
		
		
		user = userService.loginUser(username, password);
		
		if(user == null)
		{
			request.setAttribute("errorMsg", "用户和密码不存在！");
			return "login";
		}
		
		request.getSession().setAttribute(Constants.LOGIN_USER, user);
		String currentDate = DateUtils.dateToChar(new Date(), DateUtils.DATE_FORMAT_ZH) + " " +DateUtils.getDayWeek(new Date());
		request.getSession().setAttribute("currentDate", currentDate);
		
		//获取用户的操作权限
		List<Permission> operates = permissionService.findPermissionList(user.getId(), "1");
		Constants.operates = operates;
		
		return "index";
	}
	
	@RequestMapping("/logout.do") 
	public String logout(HttpServletRequest request,HttpServletResponse response)
	{
		request.getSession().removeAttribute(Constants.LOGIN_USER);
		return "login";
	}
	
	@RequestMapping("/left.do")  
	public String left(HttpServletRequest request,HttpServletResponse response)	{
		return "left";
	}
	
	@RequestMapping("/initMenus.do")
	public String initMenus(HttpServletRequest request,HttpServletResponse response)	{
		User user = (User) request.getSession().getAttribute(Constants.LOGIN_USER);
		if(user == null){
			user = userService.findUserById(1);
		}
		List<Resource> menus = resourceService.findUserResourceList(user.getId());
		
		@SuppressWarnings("unchecked")
		List<Resource> _menus = (List<Resource>) TreeUtils.addChildren(menus, null, null);
		request.setAttribute("menus", _menus);
		return "left";
	}
	
	/**
	 * 用户管理
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/userMgr.do")  
	public String userMgr(HttpServletRequest request,HttpServletResponse response){
		return"right/user/userMgr";
	}
	
	/**
	 * list.do页面开启加载，无需返回
	 * @return
	 */
	@RequestMapping("/list.do")
	public void list(HttpServletRequest request,HttpServletResponse response){
		String name = request.getParameter("name");   //接受参数
		String card = request.getParameter("card");
		String isMaster = request.getParameter("isMaster");
		
		String pageNum = request.getParameter("page");
		String pageSize= request.getParameter("rows");
		
		if(StringUtils.isEmpty(pageSize))pageSize = Constants.PAGE_SIZE;
		if(StringUtils.isEmpty(pageNum))pageNum = Constants.FIRST_PAGE_NUM;
		
		User user = (User) request.getSession().getAttribute(Constants.LOGIN_USER);   //自动抓取当前登录用户的信息
		
		if(user != null){
			//四个空字段分别为会员管理中使用到得，在user里面作为一个空字符串传递即可
			Pagination page = this.userService.findUserList("2",user.getOrgId(), user.getUserType(),name, card, "","","","",isMaster,Integer.parseInt(pageSize), Integer.parseInt(pageNum));
		    Json2Utils.parseJSON(page, response);
		}
	}
	
	//跳转修改
	@RequestMapping("/init.do")
	public String init(HttpServletRequest request,HttpServletResponse response){
		String userId = request.getParameter("userId");
		String type = request.getParameter("type");
		
		if("edit".equals(type)){//如果操作状态为编辑，则把勾选的用户信息作为一个对象传送
			User user = this.userService.findUserById(Long.parseLong(userId));
			request.setAttribute("user", user);
		}
		
		//性别级联
		List<Dictionary> sexTypes = DictUtils.getDictListByKind(DictUtils.SEX_TYPE);
		request.setAttribute("sexTypes", sexTypes);
		
		//得到当前登录人信息
		/*User us = (User) request.getSession().getAttribute(Constants.LOGIN_USER);
		int onlineUSerType = us.getUserType();   //得到当前登录人类型
		request.setAttribute("userType", userType);*/
		
		//用户类型级联
		List<Dictionary> userTypes = DictUtils.getDictListByKind(DictUtils.USER_TYPE);
		request.setAttribute("userTypes", userTypes);
		
		//传入必要的操作类型和操作id
		request.setAttribute("type", type);
		request.setAttribute("userId", userId);
		
		return "right/user/user-init";
	}
	
	//修改实现
	@RequestMapping("/update.do")
	@ResponseBody
	public String update(HttpServletRequest request,HttpServletResponse response){
		String userId = request.getParameter("userId");
		
		String truename = request.getParameter("truename").trim();
		if(!StringUtils.isEmpty(truename))truename = EscapeUtils.unescape(truename);
		
		Integer sex = Integer.parseInt(request.getParameter("sex").trim());  //  1 --  先生   0 --  小姐
		
		String email = request.getParameter("email").trim();
		if(!StringUtils.isEmpty(email))email = EscapeUtils.unescape(email);
		
		//接受手机号
		String mobile = request.getParameter("mobile");
		if(!StringUtils.isEmpty(mobile))mobile = EscapeUtils.unescape(mobile);
		
		User user = this.userService.findUserById(Long.parseLong(userId));
		//将数据存入user实体
		user.setTruename(truename);     //用户真实姓名
		user.setSex(sex);               //用户性别 
		user.setEmail(email);           //用户邮箱
		if(!StringUtils.isEmpty(mobile)){
			user.setMobile(mobile);    //用户手机
		}
		
		//调用后台
		 try {
			user = userService.updateUser(user);
		} catch (DataException e) {
			e.printStackTrace();
			return "0";
		}
		return "1";
	}
	
	/**
	 * 处理修改或者是添加
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/save.do")
	@ResponseBody
	public String save(HttpServletRequest request,HttpServletResponse response){
		String truename = request.getParameter("truename").trim();
		if(!StringUtils.isEmpty(truename))truename = EscapeUtils.unescape(truename);
		
		Integer sex = Integer.parseInt(request.getParameter("sex").trim());  //1 --  先生   0 --  小姐
		
		String username = request.getParameter("username").trim();
		if(!StringUtils.isEmpty(username))username = EscapeUtils.unescape(username);
		
		String email = request.getParameter("email").trim();
		if(!StringUtils.isEmpty(email))email = EscapeUtils.unescape(email);
		
		String mobile = request.getParameter("mobile").trim();
		if(!StringUtils.isEmpty(mobile))mobile = EscapeUtils.unescape(mobile);
		
		//用户添加人，即当前登陆用户/操作用户的信息
		User onlineUser = (User) request.getSession().getAttribute(Constants.LOGIN_USER); 
				
		//新添加用户的信息
		User user = new User();
		String password = request.getParameter("password").trim();
		if(!StringUtils.isEmpty(password))password = EscapeUtils.unescape(password);
		user.setPassword(password);     //存入用户密码
		
		//将数据存入user实体
		user.setTruename(truename);     //用户真实姓名
		user.setSex(sex);               //用户性别 
		user.setUsername(username);     //登陆名
		user.setEmail(email);           //用户邮箱
		user.setMobile(mobile);         //用户电话
		user.setLastLogin(new Date());
		user.setCreateName(onlineUser.getUsername());   //创建人信息
		user.setCreateId(onlineUser.getId());           //创建人信息
		user.setRegisterTime(new Date());
		user.setIsDelete("0");
		user.setParent(onlineUser.getId());
		user.setParentType(onlineUser.getUserType());
		user.setLocked(false);
		user.setIsMaster("1");
		user.setUserType(onlineUser.getUserType());
		
		//调用后台
		 try {
			user = userService.createUser(user,"");
		} catch (DataException e) {
			e.printStackTrace();
			return "0";
		}
		
		return "1";
	}
	
	@RequestMapping("/delete.do")
	@ResponseBody
	public String delete(HttpServletRequest request,HttpServletResponse response){
		String ids = request.getParameter("ids");
		for(String id : ids.split(",")){
			try {
				User user = this.userService.findUserById(Long.parseLong(id));
				user.setIsDelete("1");
				this.userService.updateUser(user);
			} catch (NumberFormatException e) {
				e.printStackTrace();
				return "0";
			} catch (DataException e) {
				e.printStackTrace();
				return "0";
			}
		}
		return "1";
	}
	
	/**
	 * 重置密码操作
	 * @return
	 */
	@RequestMapping("/resetPassword.do")
	@ResponseBody
	public String resetPassword(HttpServletRequest request,HttpServletResponse response){
		long id = Long.parseLong(request.getParameter("id").trim());
		
		boolean result = false;
		try {
			result = this.userService.resetPassword(id);
		} catch (DataException e) {
			e.printStackTrace();
		}
		return result?"1":"0";
	}
	
	//跳转授权页面
	@RequestMapping("/user-role.do")
	public String userRole(HttpServletRequest request,HttpServletResponse response){
		Long userId = Long.parseLong(request.getParameter("id"));
		//request.getSession().setAttribute("id", request.getParameter("id"));        //将参数转发到页面做处理
		//根据id查找出对应的角色名称
		User user = this.userService.findUserById(userId);
		request.setAttribute("user", user);
		return "right/user/user-role"; 
	}
	
	/**
	 * 授权实现
	 * 保存用户角色
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/updateRole.do")
	@ResponseBody
	public String updateRole(HttpServletRequest request,HttpServletResponse response){
		String userId = request.getParameter("userId");                      //接受需要授权的用户id
		User user = this.userService.findUserById(Long.parseLong(userId));   //返回需要授权的角色对象,使其与当前登录用户区分开
		
		String ids = request.getParameter("ids");
		//得到权限信息组
		List<Role> ur = (List<Role>) this.roleService.findRoleListByIds(ids);

		user.setRoles((Set<Role>) ListConvertToSet.convertToSet(ur));
		
		try {
			this.userService.updateUser(user);
			return "1";
		} catch (DataException e) {
			e.printStackTrace();
			return "0";
		}
	}
	
	/**
	 * 做唯一性验证
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/checkUserNameExists.do")
	@ResponseBody
	public String checkUserNameExists(HttpServletRequest request,HttpServletResponse response){
		String username = request.getParameter("username");
		if(!StringUtils.isEmpty(username))username = EscapeUtils.unescape(username);
		
		if(this.userService.checkUserNameExists(username)){   //表示查询到了数据
			return "1";
		}
		return "0";
	}
	
	@RequestMapping("/checkMobileExists.do")
	@ResponseBody
	public String checkMobileExists(HttpServletRequest request,HttpServletResponse response){
		String mobile = request.getParameter("mobile");
		if(!StringUtils.isEmpty(mobile))mobile = EscapeUtils.unescape(mobile);
		if(this.userService.checkMobileExists(mobile)){   //表示查询到了数据
			return "1";
		}
		return "0";
	}
	
	@RequestMapping("/jBoxFindUserMobile.do")
	@ResponseBody
	public String jBoxFindUserMobile(HttpServletRequest request,HttpServletResponse response){
		Long userId = Long.parseLong(request.getParameter("userId"));   //获取id
		User user = this.userService.findUserById(userId);
		if(user.getMobile() != ""){   //如果电话号码不为空，则发送数据
			request.setAttribute("user", user);
			return "1";
		}
		return "0"; 
	}
	
	/**
	 * 处理修改绑定手机号码
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/jBoxUpdateUserMobile.do")
	@ResponseBody
	public String jBoxUpdateUserMobile(HttpServletRequest request,HttpServletResponse response){
		String mobile = request.getParameter("mobile");                            //接受客户端传递的新电话号码
		Long userId = Long.parseLong(request.getParameter("userId"));              //接受客户端传递过来的id
		try {
			@SuppressWarnings("unused")
			User user = userService.updateUserMobile(userId, mobile);
			return "1";    //成功返回1
		} catch (DataException e) {
			e.printStackTrace();
			return "0";
		}
	}
	
	/**
	 * 处理修改当前登录人密码
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/modifyPassword.do")
	@ResponseBody
	public String modifyPassword(HttpServletRequest request,HttpServletResponse response){
		User onlineUser = (User) request.getSession().getAttribute(Constants.LOGIN_USER);    //得到当前登录人信息 
		
		String opwd = request.getParameter("opwd");
		String npwd = request.getParameter("npwd");
		
		try {
			return this.userService.modifyPassword(onlineUser.getId(), npwd, opwd);
		} catch (DataException e) {
			e.printStackTrace();
			return "2";
		}
	}
	
	
	/**
	 * updateLoginUser.do
	 * 修改当前登录用户/会员信息
	 */
	@RequestMapping("/updateLoginUser.do")
	public String updateLoginUser(HttpServletRequest request,HttpServletResponse response){
		List<Dictionary> sexTypes = DictUtils.getDictListByKind(DictUtils.SEX_TYPE);
		request.getSession().setAttribute("sexTypes", sexTypes);
		
		//得到当前登录人的一些必要信息
		User onlineUser = (User) request.getSession().getAttribute(Constants.LOGIN_USER);
		request.setAttribute("onlineUser", onlineUser);    //存入当前登录人对象
		
		return "common/user/userInfoMgr";
	}
	
	
	
	/**
	 * updateLoginUser.do
	 * 修改当前登录用户/会员信息
	 */
	@RequestMapping("/loginUserInit.do")
	public String loginUserInit(HttpServletRequest request,HttpServletResponse response){
		List<Dictionary> sexTypes = DictUtils.getDictListByKind(DictUtils.SEX_TYPE);
		request.getSession().setAttribute("sexTypes", sexTypes);
		
		User onlineUser = (User) request.getSession().getAttribute(Constants.LOGIN_USER);   //获取到当前登录人对象
		request.setAttribute("onlineUser", onlineUser);
		return "common/user/userInfo";
	}
}
